<template>
  <a-modal
    :visible="visible"
    @update:visible="onUpdateVisible"
    title="重新发起任务"
    :width="1200"
    @ok="handleEditSubmit"
    @cancel="handleEditCancel"
  >
    <!-- <pre>{{ editForm.message }}</pre> -->
    <a-form ref="editFormRef" :model="editForm" :rules="editFormRules" layout="vertical">
      <a-form-item v-if="editForm.message" label="审批意见">
        <a-input v-model="editForm.message" disabled />
      </a-form-item>
      <!-- 其余表单内容与 TaskAddModal.vue 一致，v-model 改为 editForm -->
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="督办来源" field="source" required>
            <a-select v-model="editForm.source" :options="options.source" placeholder="请选择督办来源" allow-clear />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="问题类型" field="problemType" required>
            <a-select
              v-model="editForm.problemType"
              :options="options.problemType"
              placeholder="请选择问题类型"
              allow-clear
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16" align="center">
        <a-col :span="12">
          <a-form-item label="督察要求" field="requirements" required>
            <a-input v-model="editForm.requirements" placeholder="请输入督察要求" />
          </a-form-item>
        </a-col>
        <a-col :span="12" style="display: flex; align-items: center">
          <label style="margin-right: 10px; min-width: 70px">领导批示</label>
          <a-checkbox v-model="editForm.leaderInstruction" style="margin-right: 24px; white-space: nowrap"
            >批示</a-checkbox
          >
          <template v-if="editForm.leaderInstruction">
            <a-input
              v-model="editForm.leaderRemark"
              placeholder="请输入批示备注"
              style="width: 180px; margin-right: 24px"
            />
            <label style="margin-right: 8px; min-width: 70px">相关文件</label>
            <a-upload v-model:file-list="editForm.leaderFiles" action="/api/upload" :limit="3" style="width: 180px" />
          </template>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="24">
          <div style="margin-bottom: 16px; display: flex; align-items: center">
            <span style="font-weight: bold">整改问题清单</span>
            <a-button type="primary" size="mini" style="margin-left: 12px" @click="addProblemRow">
              <icon-plus />
              添加一条问题
            </a-button>
          </div>
          <a-table
            class="problem-table"
            :columns="problemColumns"
            :data="editForm.problemList"
            :pagination="false"
            row-key="index"
            bordered
            style="margin-bottom: 0"
          >
            <template #problemDesc="{ record }">
              <a-textarea
                v-model="record.problemDesc"
                placeholder="请输入问题描述"
                :auto-size="{ minRows: 2, maxRows: 6 }"
              />
            </template>
            <template #action="{ rowIndex }">
              <a-button size="mini" status="danger" @click="removeProblemRow(rowIndex)"> 删除 </a-button>
            </template>
          </a-table>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="整改人员" field="rectificationUsers" required>
            <a-tree-select
              v-model="editForm.rectificationUsers"
              :data="userTreeData"
              multiple
              :field-names="{ key: 'key', title: 'name', children: 'children' }"
              placeholder="请选择整改人员"
              allow-search
              allow-clear
              @change="handleRectificationUsersChange"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="整改单位" field="rectificationUnits">
            <a-input v-model="editForm.rectificationUnits" disabled placeholder="自动填充整改单位" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="整改期限" field="rfDateRange" required>
            <a-range-picker v-model="editForm.rfDateRange" style="width: 100%" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="审核人" field="auditor" required>
            <a-tree-select
              v-model="editForm.auditor"
              :data="auditorTreeData"
              :field-names="{ key: 'key', title: 'name', children: 'children' }"
              placeholder="请选择审核人"
              allow-search
              allow-clear
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="备注" field="remark">
            <a-input v-model="editForm.remark" placeholder="请输入备注" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="相关附件" field="attachments">
            <a-upload v-model:file-list="editForm.attachments" action="/api/upload" :limit="5" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="填报单位" field="reportDeptId">
            <a-input v-model="editForm.reportDeptName" disabled />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="填报人" field="reportUserId">
            <a-input v-model="editForm.reportUser" disabled />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
  import { ref, watch, onMounted } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import { updTask, getTaskById, queryNotifyList } from '@/api/task';
  import { IconPlus } from '@arco-design/web-vue/es/icon';
  import { getUserList, queryUserByTask, queryAuditorByTask } from '@/api/user';

  // 格式化日期函数
  function formatDate(ts) {
    if (!ts) return '';
    const d = new Date(ts);
    const y = d.getFullYear();
    const m = String(d.getMonth() + 1).padStart(2, '0');
    const day = String(d.getDate()).padStart(2, '0');
    return `${y}年${m}月${day}日`;
  }
  const props = defineProps({
    visible: Boolean,
    form: Object,
    reviewMsg: String,
    options: Object,
    onRefresh: Function,
    tableData: Array,
    updateTableData: Function,
    fetchTaskList: Function,
    parentFetchTaskList: Function
  });
  const emits = defineEmits(['update:visible', 'update:opinion', 'submit', 'refresh']);
  const editFormRef = ref();
  const editForm = ref({
    taskId: null,
    source: '',
    problemType: '',
    requirements: '',
    leaderInstruction: false,
    leaderRemark: '',
    leaderFiles: [],
    problemList: [],
    rectificationUsers: [],
    rfDateRange: [],
    auditor: '',
    remark: '',
    attachments: '',
    reportDeptId: null,
    reportDeptName: '',
    reportUserId: null,
    reportUser: '',
    rectificationUnits: '',
    message: ''
  });
  const userTreeData = ref([]);
  const auditorTreeData = ref([]);

  // 定义问题列表表格列
  const problemColumns = [
    { title: '序号', dataIndex: 'index', width: 60 },
    { title: '问题描述', dataIndex: 'problemDesc', slotName: 'problemDesc' },
    { title: '操作', dataIndex: 'action', width: 60, slotName: 'action' }
  ];
  watch(
    () => props.form,
    val => {
      if (val) {
        editForm.value = JSON.parse(JSON.stringify(val));
        // 处理整改期限回显 - 将时间戳转换为Date对象
        if (val.rfStartDate && val.rfEndDate) {
          editForm.value.rfDateRange = [new Date(val.rfStartDate), new Date(val.rfEndDate)];
        } else {
          editForm.value.rfDateRange = [];
        }
        // 处理整改人员回显 - 将字符串转换为数组
        if (val.rfUsers && typeof val.rfUsers === 'string') {
          editForm.value.rectificationUsers = val.rfUsers.split(',').map(id => parseInt(id.trim()));
        } else if (Array.isArray(val.rfUsers)) {
          editForm.value.rectificationUsers = val.rfUsers;
        } else {
          editForm.value.rectificationUsers = [];
        }
        // 处理整改单位回显 - 根据整改人员自动计算单位名称
        if (val.rfUsers && typeof val.rfUsers === 'string') {
          const userIds = val.rfUsers.split(',').map(id => parseInt(id.trim()));
          // 延迟计算单位名称，等userTreeData加载完成后再计算
          setTimeout(() => {
            calculateRectificationUnits(userIds);
          }, 500);
        } else if (Array.isArray(val.rfUsers)) {
          setTimeout(() => {
            calculateRectificationUnits(val.rfUsers);
          }, 500);
        } else {
          editForm.value.rectificationUnits = '';
        }
        // 确保 problemList 存在
        if (!editForm.value.problemList) {
          editForm.value.problemList = [];
        }
      }
    },
    { immediate: true, deep: true }
  );

  const editFormRules = {
    source: [{ required: true, message: '请选择督办来源' }],
    problemType: [{ required: true, message: '请选择问题类型' }],
    requirements: [{ required: true, message: '请输入督察要求' }],
    rectificationUsers: [{ required: true, message: '请选择整改人员' }],
    rfDateRange: [{ required: true, message: '请选择整改期限' }],
    auditor: [{ required: true, message: '请选择审核人' }]
  };

  function addProblemRow() {
    editForm.value.problemList.push({ index: editForm.value.problemList.length + 1, problemDesc: '' });
  }
  function removeProblemRow(idx) {
    editForm.value.problemList.splice(idx, 1);
    editForm.value.problemList.forEach((item, i) => (item.index = i + 1));
  }

  function calculateRectificationUnits(userIds) {
    // 获取所有用户节点的映射关系
    const userGroupMap = new Map();
    userTreeData.value.forEach(group => {
      group.children.forEach(user => {
        userGroupMap.set(user.key, {
          userId: user.key,
          groupId: group.userId,
          groupName: group.name,
          userName: user.name
        });
      });
    });

    // 根据用户ID获取对应的组织信息
    const selectedGroups = new Map();
    userIds.forEach(userId => {
      const userInfo = userGroupMap.get(userId);
      if (userInfo) {
        selectedGroups.set(userInfo.groupId, userInfo.groupName);
      }
    });

    // 更新整改单位显示
    const unitNames = Array.from(selectedGroups.values());
    editForm.value.rectificationUnits = unitNames.join(', ');
  }

  function handleRectificationUsersChange(value) {
    // 获取所有用户节点的映射关系
    const userGroupMap = new Map();
    userTreeData.value.forEach(group => {
      group.children.forEach(user => {
        userGroupMap.set(user.key, {
          userId: user.userId,
          groupId: group.userId,
          groupName: group.name,
          userName: user.name
        });
      });
    });

    // 根据选中的用户key获取对应的组织信息
    const selectedGroups = new Map();
    const selectedUserKeys = value;

    selectedUserKeys.forEach(userKey => {
      const userInfo = userGroupMap.get(userKey);
      if (userInfo) {
        if (selectedGroups.has(userInfo.groupId)) {
          // 发现重复组织
          Message.error('一个组织只能有一个整改接收人');
          // 移除重复的选择
          const newValue = value.filter(key => key !== userKey);
          editForm.value.rectificationUsers = newValue;
          return;
        }
        selectedGroups.set(userInfo.groupId, userInfo.groupName);
      }
    });

    // 更新整改单位显示
    editForm.value.rectificationUnits = Array.from(selectedGroups.values()).join(', ');
  }

  async function fetchUserTreeData() {
    try {
      const res = await queryUserByTask();
      const tree = [];
      if (res && res.data) {
        Object.entries(res.data).forEach(([groupId, userList]) => {
          if (userList.length > 0) {
            tree.push({
              key: `group_${groupId}`,
              userId: Number(groupId),
              name: userList[0].groupName,
              selectable: false,
              children: userList.map(user => ({
                key: user.userId,
                name: user.name + '-' + (user.deptName || '')
              }))
            });
          }
        });
      }
      userTreeData.value = tree;

      // 数据加载完成后，重新计算整改单位名称
      if (editForm.value.rectificationUsers && editForm.value.rectificationUsers.length > 0) {
        calculateRectificationUnits(editForm.value.rectificationUsers);
      }
    } catch (e) {
      Message.error('获取整改人员失败');
    }
  }

  function onUpdateVisible(val) {
    emits('update:visible', val);
  }
  async function fetchAuditorTreeData() {
    try {
      const res = await queryAuditorByTask();
      const tree = [];
      if (res && res.data) {
        Object.entries(res.data).forEach(([groupId, userList]) => {
          if (userList.length > 0) {
            tree.push({
              key: `group_${groupId}`,
              userId: Number(groupId),
              name: userList[0].groupName,
              selectable: false,
              children: userList.map(user => ({
                key: user.userId,
                name: user.name + '-' + (user.deptName || '')
              }))
            });
          }
        });
      }
      auditorTreeData.value = tree;
    } catch (e) {
      Message.error('获取审核人失败');
    }
  }

  function handleEditCancel() {
    emits('update:visible', false);
  }
  function handleEditSubmit() {
    editFormRef.value.validate().then(async () => {
      try {
        const payload = { ...editForm.value };

        if (!payload.taskId) {
          Message.error('缺少任务ID，无法更新');
          return;
        }

        // 确保字段名正确
        payload.reportDeptId = payload.reportDeptId;
        payload.reportUserId = payload.reportUserId;

        // 处理整改人员：数组转字符串
        if (Array.isArray(payload.rectificationUsers)) {
          payload.rfUsers = payload.rectificationUsers.join(',');
        } else {
          payload.rfUsers = '';
        }

        // 处理整改单位：根据整改人员计算单位ID
        if (Array.isArray(payload.rectificationUsers) && payload.rectificationUsers.length > 0) {
          const userGroupMap = new Map();
          userTreeData.value.forEach(group => {
            group.children.forEach(user => {
              userGroupMap.set(user.key, {
                userId: user.key,
                groupId: group.userId,
                groupName: group.name,
                userName: user.name
              });
            });
          });

          const selectedGroups = new Set();
          payload.rectificationUsers.forEach(userId => {
            const userInfo = userGroupMap.get(userId);
            if (userInfo) {
              selectedGroups.add(userInfo.groupId);
            }
          });

          payload.rfUnits = Array.from(selectedGroups).join(',');
        } else {
          payload.rfUnits = '';
        }

        if (Array.isArray(payload.rfDateRange) && payload.rfDateRange.length === 2) {
          const [start, end] = payload.rfDateRange;
          payload.rfStartDate = start ? new Date(start).getTime() : '';
          payload.rfEndDate = end ? new Date(end).getTime() : '';
        }
        delete payload.rfDateRange;
        delete payload.rectificationUsers;
        delete payload.rectificationUnits;

        if (payload.attachments && payload.attachments.length) {
          payload.attachments = payload.attachments.map(f => f.url || f.response?.url || f);
        }
        const result = await updTask(payload);

        if (result && (result.code === 200 || result.code === 0)) {
          Message.success('重新发起成功');

          // 触发父组件刷新
          if (props.parentFetchTaskList) {
            props.parentFetchTaskList();
          }

          // 关闭弹窗
          emits('update:visible', false);
        } else {
          Message.error(result?.message || '重新发起失败');
        }
      } catch (e) {
        Message.error('重新发起失败');
        // 失败时也关闭弹窗
        emits('update:visible', false);
      }
    });
  }

  onMounted(async () => {
    await fetchUserTreeData();
    await fetchAuditorTreeData();
  });
</script>
